﻿using Orchard.ContentManagement.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using EcoTourEduca.BingYourMaps.Models;
using Orchard.Data;
using Orchard.ContentManagement;
using EcoTourEduca.BingYourMaps.Services;

namespace EcoTourEduca.BingYourMaps.Handlers
{
    public class BingMapsLocationHandler : ContentHandler
    {
        private readonly IContentManager _contentManager;
        private readonly IBingYourMapsService _service;
        private readonly IRepository<BingMapsLocationRecord> _repository;

        public BingMapsLocationHandler(IRepository<BingMapsLocationRecord> repository 
                                ,IBingYourMapsService service
                                ,IContentManager contentManager)
        {
            Filters.Add(StorageFilter.For(repository));
            _repository = repository;
            _contentManager = contentManager;
            _service = service;

            //OnInitializing<BingMapsLocationPart>(PropertySetHandlers);
            //OnLoaded<BingMapsLocationPart>(LazyLoadHandlers);
            OnRemoved<BingMapsLocationPart>(LocationMappingRemovalHandler);
        }

        private void LocationMappingRemovalHandler(RemoveContentContext context, BingMapsLocationPart locationPart)
        {
            if (locationPart != null)
            {
                _service.RemoveMappingsForBingMapsLocation(locationPart);
                _repository.Delete(locationPart.Record); // Base Handler doesn't by default remove part records
            }
        }

        //private void LazyLoadHandlers(LoadContentContext context, BingMapsLocationPart locationPart)
        //{
        //    // Lazy load BingMapAreas for BingMapsLocation
        //    locationPart.BingMapsAreasField.Loader(() =>
        //        locationPart.BingMapsAreas == null ? 
        //        null 
        //        : _service.GetBingMapsAreaPartsForLocationPart(locationPart.Id));
        //}

        //private void PropertySetHandlers(InitializingContentContext context, BingMapsLocationPart part)
        //{
        //    // TODO?
        //}
    }
}